package org.ucas.faker.web.utils.feature;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.ucas.faker.web.entity.Depot;
import org.ucas.faker.web.entity.patents.PatentWrapper;
import org.ucas.faker.web.model.KeywordNode;
import org.ucas.faker.web.service.DepotService;
import org.ucas.faker.web.service.PatentService;
import org.ucas.faker.web.utils.tech.PatentFeaturizeWithKeywordTree;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class FeatureGenTask {
  private static final List<FeatureGenerator> generators = new ArrayList<FeatureGenerator>() {{
    add(new TechGenerator());
  }};

  @Autowired
  private PatentService patentService;

  @Autowired
  private DepotService depotService;

  public void genFeature(long depotId) {
    List<PatentWrapper> patents = patentService.toGenerate(depotId);
    for (PatentWrapper patent : patents) {
      for (FeatureGenerator generator : generators) generator.generate(patent);
      if (patent.getFeature().getId() == null) patent.getFeature().setId(patent.getId());
      patentService.persistFeature(patent.getFeature());
    }
  }

  public void genFeature(long depotId, List<KeywordNode> tree) {
    List<PatentWrapper> patents = patentService.toGenerate(depotId);
    List<String> tree_branch = new ArrayList<>();
    List<String> tree_effect = new ArrayList<>();
    KeywordNode.GetBranchAndEffect(tree, tree_branch, tree_effect);

//	    System.out.println("\n\n\n****************\n");
//	    System.out.println(tree_branch);
//	    System.out.println(tree_effect);

    PatentFeaturizeWithKeywordTree pf = new PatentFeaturizeWithKeywordTree(tree_branch, tree_effect);

    for (PatentWrapper patent : patents) {
      System.out.println(patent.getContent().getTi());
      for (FeatureGenerator generator : generators) generator.generate(patent, pf);
      if (patent.getFeature().getId() == null) patent.getFeature().setId(patent.getId());
      patentService.persistFeature(patent.getFeature());
    }

    Depot depot = depotService.load(depotId);
    depot.setLastAnalysis(new Date());
    depotService.persist(depot);
  }

  public void syncGenFeature(long depotId, List<KeywordNode> tree) {
    genFeature(depotId, tree);
  }

  @Async("featureAsync")
  public void asyncGenFeature(long depotId, List<KeywordNode> tree) {
    genFeature(depotId, tree);
  }

  public void syncGenFeature(long depotId) {
    genFeature(depotId);
  }

  @Async("featureAsync")
  public void asyncGenFeature(long depotId) {
    genFeature(depotId);
  }

}
